<template>
  <div class="select-page-container">
    <h2>SelectPage 示例 (Element Plus)</h2>

    <el-select
      v-model="selectedValue"
      :placeholder="getPlaceholder"
      :popper-append-to-body="false"
      @visible-change="handleVisibleChange"
      class="select-component"
      multiple
    >
      <template #dropdown>
        <div class="custom-dropdown">
          <el-input
            v-model="searchQuery"
            placeholder="搜索..."
            size="small"
            clearable
            @input="handleSearch"
            class="search-input"
          />

          <!-- Use <template> tag to group conditional elements -->
          <template v-if="loading">
            <el-loading class="loading-state">
              <template #default>
                <span class="loading-text">加载中...</span>
              </template>
            </el-loading>
          </template>
          <template v-else-if="currentPageItems.length > 0">
            <el-table
              :data="currentPageItems"
              style="width: 100%"
              @row-click="handleRowClick"
              :row-selection="rowSelection"
            >
              <el-table-column type="selection" v-if="isMultiple" />
              <el-table-column prop="name" label="名称" />
              <el-table-column prop="description" label="描述" />
            </el-table>
          </template>
          <div v-else class="no-result">无匹配结果</div>

          <el-pagination
            v-if="total > 0"
            small
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            layout="prev, pager, next"
            @current-change="handlePageChange"
            class="pagination"
          />
        </div>
      </template>
    </el-select>

    <div class="selected-info" v-if="selectedValue">
      <el-card>
        <template #header>已选择信息</template>
        <p v-if="isMultiple">ID: {{ selectedValue.join(', ') }}</p>
        <p v-else>ID: {{ selectedValue }}</p>
        <p v-if="isMultiple">名称: {{ selectedLabel.join(', ') }}</p>
        <p v-else>名称: {{ selectedLabel }}</p>
        <p v-if="isMultiple">
          描述:
          {{ selectedItem.map(item => item.description).join('; ') || '无' }}
        </p>
        <p v-else>描述: {{ selectedItem?.description || '无' }}</p>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { ElLoading, ElTable, ElTableColumn } from 'element-plus';

// 控制单选或多选，true 为多选，false 为单选
const isMultiple = ref(true);

// State management
const selectedValue = ref(isMultiple.value ? [] : null);
const selectedLabel = ref(isMultiple.value ? [] : '');
const selectedItem = ref(isMultiple.value ? [] : null);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const allItems = ref([]);
const loading = ref(false);

// Computed property to generate placeholder string
const getPlaceholder = computed(() => {
  if (selectedValue.value.length > 0) {
    if (isMultiple.value) {
      return selectedLabel.value.join(', ');
    }
    return selectedLabel.value;
  }
  return '请选择';
});

// 计算当前页数据
const currentPageItems = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  return allItems.value.slice(startIndex, startIndex + pageSize.value);
});

// 生成模拟数据
const generateMockData = (count) => {
  return Array.from({ length: count }, (_, i) => ({
    id: i + 1,
    name: `选项 ${i + 1}`,
    description: `这是选项 ${i + 1} 的详细描述信息，用于展示更多内容`
  }));
};

// 加载数据
const loadData = async (query = '') => {
  loading.value = true;

  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 500));

  // 生成基础数据
  const baseData = generateMockData(50);

  // 根据搜索词过滤
  const filteredData = query
    ? baseData.filter(item =>
        item.name.toLowerCase().includes(query.toLowerCase()) ||
        item.description.toLowerCase().includes(query.toLowerCase())
      )
    : baseData;

  allItems.value = filteredData;
  total.value = filteredData.length;
  loading.value = false;
};

// 处理搜索
const handleSearch = (query) => {
  currentPage.value = 1; // 重置页码
  loadData(query);
};

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  // 滚动到选项列表顶部
  const selectDropdown = document.querySelector('.el-select-dropdown__wrap');
  if (selectDropdown) selectDropdown.scrollTop = 0;
};

// 处理下拉框显示/隐藏
const handleVisibleChange = (visible) => {
  if (visible && allItems.value.length === 0) {
    loadData(); // 首次打开时加载数据
  }
};

// 处理行点击事件
const handleRowClick = (row) => {
  if (isMultiple.value) {
    const index = selectedValue.value.indexOf(row.id);
    if (index === -1) {
      selectedValue.value.push(row.id);
      selectedLabel.value.push(row.name);
      selectedItem.value.push(row);
    } else {
      selectedValue.value.splice(index, 1);
      selectedLabel.value.splice(index, 1);
      selectedItem.value.splice(index, 1);
    }
  } else {
    selectedValue.value = row.id;
    selectedLabel.value = row.name;
    selectedItem.value = row;
  }
};

// 表格行选择配置
const rowSelection = computed(() => ({
  selectedRowKeys: selectedValue.value,
  onChange: (selectedRowKeys, selectedRows) => {
    if (isMultiple.value) {
      selectedValue.value = selectedRowKeys;
      selectedLabel.value = selectedRows.map(row => row.name);
      selectedItem.value = selectedRows;
    }
  }
}));

// 监听选中值变化，更新显示信息
watch(selectedValue, (value) => {
  if (isMultiple.value) {
    if (value.length === 0) {
      selectedLabel.value = [];
      selectedItem.value = [];
    }
  } else {
    if (value) {
      const item = allItems.value.find(item => item.id === value);
      if (item) {
        selectedLabel.value = item.name;
        selectedItem.value = item;
      }
    } else {
      selectedLabel.value = '';
      selectedItem.value = null;
    }
  }
});

// 初始化
loadData();
</script>

<style scoped>
.select-page-container {
  max-width: 600px;
  margin: 2rem auto;
  padding: 0 1rem;
}

h2 {
  color: #333;
  text-align: center;
  margin-bottom: 2rem;
}

.select-component {
  width: 100%;
}

.search-input {
  width: 100%;
  margin-bottom: 8px;
}

.custom-dropdown {
  padding: 8px;
}

.el-table {
  margin-bottom: 8px;
}

.no-result {
  text-align: center;
  padding: 1rem 0;
}

.pagination {
  margin-top: 8px;
  text-align: right;
}

.loading-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 1rem 0;
}

.loading-text {
  margin-left: 8px;
  color: #666;
}

.selected-info {
  margin-top: 1rem;
}
</style>
